<template>
  <div v-if="complete">
    <div>
      <el-form ref="form" :model="form" label-width="150px" style="width=50%">
        <el-form-item>
          <el-select
            v-model="clsName"
            placeholder="请选择要实例化的策略模板"
            filterable
            style="width:350px"
            @change="fetchStrategyParams()"
          >
            <el-option
              v-for="item in strategyClasses"
              :key="item.cls"
              :value="item.cls"
              :label="item.cls +'-' + item.brief + '-' + item.author"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-for="item in strategyInsInput"
          :key="item.key"
          :label="item.key"
          style="width:500px"
        >
          <el-input v-model="form[item.key]" :placeholder="item.name" @input="oninput" />
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" @click="initStrategy()">初始化策略</el-button>
  </div>
</template>

<script>
import { getStrategClsParams, getStrategClsses, postInitStrategy } from '@/api/strategy'
export default {
  name: 'ConfigStrategyInitPage',

  data() {
    return {
      complete: false,
      clsName: '',
      form: {
      },
      strategyClasses: [],
      strategyInsInput: []
    }
  },

  mounted() {
    this.fetchStrateyList()
  },

  methods: {
    fetchStrateyList() {
      getStrategClsses().then((response) => {
        this.strategyClasses = response.data
        console.log(response.data)
        this.complete = true
      })
    },
    fetchStrategyParams() {
      const clsName = this.clsName
      getStrategClsParams(clsName).then((response) => {
        this.strategyInsInput = response.data
        response.data.forEach(element => {
          this.form[element.key] = element.default
        })
      })
    },
    initStrategy() {
      this.form.clsName = this.clsName
      postInitStrategy(this.form).then((response) => {
        if (response.data.code === 20000) {
          this.$notify({
            title: '成功',
            message: '初始化策略成功',
            type: 'success'
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: `初始化策略失败：${response.data}`
          })
        }
      })
    },
    oninput() {
      this.$forceUpdate()
    }
  }
}
</script>
